from typing import List
from fastapi import APIRouter, Security, Path
from package.fastapi import permission
from package.fastapi.schema import BatchId
from fastapi import File, UploadFile
from fastapi.responses import FileResponse
from .view import FileView

router_directory = APIRouter(prefix='/directory', tags=['FileServer'])
router_meta_directory = {'module': 'System', 'sub_module': 'Directory'}

router_file = APIRouter(prefix='/file', tags=['FileServer'])
router_meta = {'module': 'System', 'sub_module': 'File'}


@router_directory.get('/{directory:path}', openapi_extra=router_meta_directory, name='directory_list',
                      summary='文件夹列表获取')
def directory_list(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
                   user=Security(permission.security, scopes=['file:read'])):
    return FileView.list_directory(directory)


@router_directory.post('/{directory:path}', openapi_extra=router_meta_directory, name='directory_post',
                       summary='文件夹创建')
def directory_post(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
                   user=Security(permission.security, scopes=['file:write'])):
    return FileView.post_directory(directory)


@router_directory.delete('/{directory:path}', openapi_extra=router_meta_directory, name='directory_delete',
                         summary='文件夹删除')
def directory_delete(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
                     user=Security(permission.security, scopes=['file:write'])):
    return FileView.delete_directory(directory)


@router_file.get('/{directory:path}/{filename}', openapi_extra=router_meta, name='file_get', summary='文件获取')
def file_get(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
             filename: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
             user=Security(permission.security, scopes=['file:read'])):
    return FileResponse(**FileView.get_file(directory, filename))


@router_file.post('/{directory:path}', openapi_extra=router_meta, name='file_post', summary='文件上传')
def file_post(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
              files: List[UploadFile] = File(...),
              user=Security(permission.security, scopes=['file:write'])):
    return FileView.post_file(directory, files)


@router_file.delete('/{directory}', openapi_extra=router_meta, name='file_delete', summary='文件删除')
def file_delete(directory: str = Path(regex='^[a-zA-Z0-9_.-/]+'),
                body: BatchId = None,
                user=Security(permission.security, scopes=['file:write'])):
    return FileView.delete_file(directory, filenames=body.ids)
